package com.linxianqin.restTemplate.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lxq
 * @version 1.0
 * @description: 通过 restTemplate 发送get请求
 * @date 2021/1/14 15:38
 */
@Slf4j
@RestController
public class GetController {
    private RestTemplate restTemplate;
    public GetController(RestTemplate restTemplate){
        this.restTemplate=restTemplate;
    }
    /**
     * get不带参数
     * @return
     */
    @GetMapping("/getForObject")
    public String getForObject(){
        String url="http://localhost:8092/test/hello";
        String result =restTemplate.getForObject(url,String.class);
        return result;
    }

    /**
     * get不带参数
     * @return
     */
    @GetMapping("/getForEntity")
    public String getForEntity(){
        String url="http://localhost:8092/test/hello";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String body = responseEntity.getBody();
        HttpStatus statusCode = responseEntity.getStatusCode();
        int statusCodeValue = responseEntity.getStatusCodeValue();
        HttpHeaders headers = responseEntity.getHeaders();
        StringBuffer result = new StringBuffer();
        result.append("responseEntity.getBody()：").append(body).append("<hr>")
                .append("responseEntity.getStatusCode()：").append(statusCode).append("<hr>")
                .append("responseEntity.getStatusCodeValue()：").append(statusCodeValue).append("<hr>")
                .append("responseEntity.getHeaders()：").append(headers).append("<hr>");
        return result.toString();
    }

    /**
     * get带参数
     * @return
     */
    @GetMapping("/getForExchange")
    public String getForExchange(){
        String url="http://localhost:8092/test/hello";
        String timeStramp = String.valueOf(System.currentTimeMillis());
        HttpHeaders headers = new HttpHeaders();
        headers.add("appid", "");
        headers.add("timestamp", timeStramp);
        JSONObject jsonObj = new JSONObject();
        HttpEntity<String> formEntity = new HttpEntity<>(null, headers);
        Map<String, Object> maps = new HashMap<>();
        maps.put("sql", "select * from jingfen.d_user_city");
        maps.put("type", 1);
        maps.put("account", "admin_test");
        ResponseEntity<String> exchange = restTemplate.exchange(url + "?sql={sql}&amp;type={type}&amp;account={account}", HttpMethod.GET,formEntity, String.class, maps);
        String body = exchange.getBody();
        return body;
    }
}
